//
//  MapViewController.m
//  FiltrationSystem
//
//  Created by 123456 on 2017/1/23.
//  Copyright © 2017年 YTYangK. All rights reserved.
//

#import "MapViewController.h"
//显示地图
#import <MapKit/MapKit.h>
//定位
#import <CoreLocation/CoreLocation.h>
#import "KCAnnotation.h"
#import "NavigationView.h"


@interface MapViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
{
    CLLocationManager *_locationManager;
    KCAnnotation *annotation1;//大头针
    NSDictionary* parameterDic;
    NavigationView *Nview;//导航头
    BOOL _firstDisplay; //是否第一loading
    float latitude;
    float longitude;
}

@property (nonatomic,strong) MKMapView *_mapView;
@property (nonatomic,strong) CLGeocoder *geocoder;
@property (nonatomic,strong)NSMutableArray *AnnotationAry;

@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self updateUI];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [self deleteAll];
    [self requestURLwithViewForMap];
    
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    _firstDisplay=NO;
}


-(void)updateUI{

    self.title = @"地图";
    _firstDisplay = YES;

    self._mapView  = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, self.view.size.width, self.view.size.height)];
    //设置代理
    self._mapView.delegate=self;
    [self.view addSubview:self._mapView];
    
    
    UIButton *locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    locationButton.backgroundColor = [UIColor clearColor];
    locationButton.frame =CGRectMake(15, self.view.size.height-150, 50, 50);
    
    [locationButton setImage:[UIImage imageNamed:@"标记按钮"] forState:UIControlStateNormal];
    
    [locationButton addTarget:self action:@selector(locationButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:locationButton];
    
    
    
    
//    请求定位服务
    _locationManager=[[CLLocationManager alloc]init];

    if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
        [_locationManager requestWhenInUseAuthorization];

    }

    //用户位置追踪(用户位置追踪用于标记用户当前位置，此时会调用定位服务)
    self._mapView.userTrackingMode=MKUserTrackingModeFollow;
    //设置地图类型
    self._mapView.mapType=MKMapTypeStandard;
    self._mapView.showsUserLocation = YES;
    //设置定位精度
    _locationManager.desiredAccuracy=kCLLocationAccuracyBestForNavigation;
    //定位频率,每隔多少米定位一次
    CLLocationDistance distance=20.0;//十米定位一次
    _locationManager.distanceFilter=distance;


    ////    启动跟踪定位
    [_locationManager startUpdatingLocation];

    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        //添加大头针
        [self requestURLwithViewForMap];

    });


}


#pragma mark -- CLLocationManagerDelegate

#pragma mark - 地图控件代理方法
#pragma mark 更新用户位置，只要用户改变则调用此方法（包括第一次定位到用户位置）
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    



}

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        static NSString *key1=@"AnnotationKey1";
        MKAnnotationView *annotationView=[self._mapView dequeueReusableAnnotationViewWithIdentifier:key1];

        //如果缓存池中不存在则新建
        if (!annotationView) {
            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout=true;//允许交互点击
//          annotationView.animatesDrop = YES;
            annotationView.calloutOffset=CGPointMake(0, 0);//定义详情视图偏移量
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            [button setBackgroundImage:[UIImage imageNamed:@"进入列表按钮"] forState:UIControlStateNormal];
            button.backgroundColor = [UIColor clearColor];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.frame = CGRectMake(0, 0, 60, 50);
            [button addTarget:self action:@selector(NavigationButton) forControlEvents:UIControlEventTouchUpInside];
            annotationView.rightCalloutAccessoryView = button;
            
        }
        
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        annotationView.annotation=annotation;
        annotationView.image=((KCAnnotation *)annotation).image;//设置大头针视图的图片

        return annotationView;
    }else {
        return nil;
    }
}

#pragma mark 选中标注的处理事件
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    //显示选中大头针偏移为中心
    [self._mapView setCenterCoordinate:view.annotation.coordinate animated:YES];
    
    //记录当前大头针坐标用于调用导航
    latitude =view.annotation.coordinate.latitude;
    longitude =view.annotation.coordinate.longitude;
    
    //显示导航View
    [UIView animateWithDuration:0.4  animations:^{
        CGRect btnFrame = Nview.frame;
        btnFrame.origin.y = 0;
        Nview.frame = btnFrame;
    }];
        //导航View的Title
    Nview.NavigationTitle.text = [NSString stringWithFormat:@"%@%@",view.annotation.title,view.annotation.subtitle];
    

    
    
}

#pragma mark 取消选中标注的处理事件
-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
    NSLog(@"取消了标注");

}


//定位个人位置显示，开启跟踪
- (void)locationButton {
    
    CLLocationCoordinate2D coord = self._mapView.userLocation.coordinate;
    MKCoordinateSpan span = { 0.01, 0.01 };
    MKCoordinateRegion region = { coord, span };
    [self._mapView setRegion:region animated:YES];

}


/**
 * 添加新设备时重新请求地图所有大头针坐标
 */
- (void)requestURLwithViewForMap{
            CLLocationCoordinate2D location1=CLLocationCoordinate2DMake(22.218878,113.487100);
    
            //地理编码类
            CLGeocoder *geocoder = [[CLGeocoder alloc]init];
            //生成一个location
            CLLocation *location = [[CLLocation alloc]initWithLatitude:22.218878 longitude:113.487100];
           
            [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
                if (error)
                {
                    NSLog(@"反向地理编码失败,error==%@",error);
                }else
                {
                    annotation1=[[KCAnnotation alloc]init];
                    CLPlacemark *mark = [placemarks firstObject];
                    annotation1.title=[NSString stringWithFormat:@"%@%@%@",mark.country,mark.administrativeArea,mark.locality];
                    annotation1.subtitle=[NSString stringWithFormat:@"%@%@",mark.subLocality,mark.name];
                    annotation1.image = [UIImage imageNamed:@"坐标"];
                    annotation1.coordinate=location1;
                    
                    NSLog(@"反向地理编码,==%@=%@=%@=%@=%@=%@=%@=%@=%@=%@=%@=%@",mark.name,mark.thoroughfare,mark.subThoroughfare,mark.locality,mark.subLocality,mark.administrativeArea,mark.subAdministrativeArea,mark.postalCode,mark.ISOcountryCode,mark.country,mark.inlandWater,mark.ocean);

                    [self.AnnotationAry addObject:annotation1];
                    [self._mapView addAnnotations:self.AnnotationAry];
                    [self._mapView selectAnnotation:annotation1 animated:YES];

                    
                }
                
                if (_firstDisplay == YES) {
                [self._mapView showAnnotations:self._mapView.annotations animated:YES];
                }
            }];

    
        //添加导航View
        [Nview removeFromSuperview];
        Nview = [[NSBundle mainBundle]loadNibNamed:@"NavigationView" owner:self options:nil][0];
        Nview.frame = CGRectMake(10, -50, self.view.frame.size.width-20, 50);
        [Nview.NavigationButton addTarget:self action:@selector(NavigationButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view insertSubview:Nview atIndex:2];



}



//调用系统导航
-(void)NavigationButton:(UIButton *)button
{
    
    [self Navigation];
   
    
}

-(void)NavigationButton{
    
    [self Navigation];

}


-(void)Navigation{
    UIAlertController* alerController = [UIAlertController alertControllerWithTitle:@"导航" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction* gaodeMapAction = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction* _Nonnull action) {
                                                               
                                                               
                                                               
                                                               //新方法星期一测试
                                                               NSString * urlstring = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &backScheme=&lat=%f&lon=%f&dev=0&style=2",latitude,longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                                                               
                                                               
                                                               [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlstring]];
                                                               
                                                           }];
    
    UIAlertAction* baiduMapAction = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction* _Nonnull action) {
                                                               //新方法星期一测试
                                                               NSString * urlstring = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",latitude,longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                                                               
                                                               
                                                               
                                                               [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlstring]];
                                                           }];
    
    UIAlertAction* ownMapAction = [UIAlertAction actionWithTitle:@"自带地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
        
        CLLocation *location = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
        _geocoder=[[CLGeocoder alloc]init];
        //    注意地理编码一次只能定位到一个位置，不能同时定位，所在放到第一个位置定位完成回调函数中再次定位
        [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
            if (error){
                NSLog(@"反向地理编码失败,error==%@",error);
            }else{
                CLPlacemark *clPlacemark2=[placemarks firstObject];//获取第一个地标
                MKPlacemark *mkPlacemark2=[[MKPlacemark alloc]initWithPlacemark:clPlacemark2];
                NSDictionary *options=@{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard),MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving};
                MKMapItem *mapItem1=[MKMapItem mapItemForCurrentLocation];//当前位置
                MKMapItem *mapItem2=[[MKMapItem alloc]initWithPlacemark:mkPlacemark2];
                [MKMapItem openMapsWithItems:@[mapItem1,mapItem2] launchOptions:options];
            }
            
        }];
        
    }];
    
    [alerController addAction:cancelAction];
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]) {
        [alerController addAction:baiduMapAction];
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        [alerController addAction:gaodeMapAction];
    };
    
    [alerController addAction:ownMapAction];
    if (objc_getClass("UIAlertController") != nil) {
        [self presentViewController:alerController animated:YES completion:nil];
    }
    
    
    
}

-(NSMutableArray *)AnnotationAry
{
    if (!_AnnotationAry) {
        _AnnotationAry = [[NSMutableArray alloc]init];
    }
    return _AnnotationAry;
}



- (void)deleteAll
{
    //删除地图上所有的大头针
    [self._mapView removeAnnotations:self._mapView.annotations];
}






@end
